package com.kindnesslibrary.activity.adapter;

import android.app.Activity;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import com.kindnesslibrary.R;
import com.kindnesslibrary.base.BaseApplication;
import com.kindnesslibrary.model.XImageModel;
import com.kindnesslibrary.photoview.PhotoView;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;

/**
 * Created by lenovo on 2017/6/26.
 * 预览图片适配器
 */
public class XImagePagerAdapter extends PagerAdapter {

    ArrayList<XImageModel> xImageModels; // 所有图片，如果没有被选择的图片则使用该集合资源
    ArrayList<String> imageList; // 选择的图片列表
    XImagePagerListener xImagePagerListener; // 图片监听器
    Activity context;

    public XImagePagerAdapter(Activity context, ArrayList<XImageModel> xImageModels, ArrayList<String> imageList,
                              XImagePagerListener xImagePagerListener){
        this.context = context;
        this.xImageModels = xImageModels;
        this.imageList = imageList;
        this.xImagePagerListener = xImagePagerListener;
    }

    @Override
    public int getCount() {
        return imageList.size() > 0 ? imageList.size() :
                xImageModels.size();
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        String imgPath = "";
        if(imageList.size() > 0){
            imgPath = imageList.get(position);
        }else{
            imgPath = xImageModels.get(position).filePath;
        }
        View preview = context.getLayoutInflater().inflate(R.layout.item_ximage_preview_layout, null);
        PhotoView photoView = (PhotoView) preview.findViewById(R.id.pv_ximage_preview_image);
        container.addView(preview);
        ImageLoader.getInstance().displayImage("file://" + imgPath, photoView, BaseApplication.getInstance().options, null);
        photoView.setOnClickListener(view -> {
            if(xImagePagerListener != null){
                xImagePagerListener.onClick();
            }
        });
        return preview;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    public ArrayList<String> getImageList() {
        return imageList;
    }

    public ArrayList<XImageModel> getxImageModels() {
        return xImageModels;
    }

    public interface XImagePagerListener{
        void onClick();
    }

}
